#include "project.h"
#include <QString>
#include <QObject>
#include "form2_1.h"
#include "form2_2.h"
#include "form2_2_1.h"
#include "form2_4.h"
#include "form1_1.h"
#include "form2_5.h"
#include "form3_1.h"
#include "form2_4_2.h"
#include "form3_2.h"
#include "widget.h"

using namespace std;


// 从文件加载航班信息
void FlightBookingSystem::loadFlightsFromFile(const string& filename) {
    ifstream file(filename);
    if (!file.is_open()) {
        cout << "无法打开航班数据文件以加载" << endl;
        return;
    }

    // 从文件中读取航班信息并存储到 flights 向量中
    string line;
    while (getline(file, line)) {
        // 解析航班信息并添加到 flights 向量中
        // 格式：目的地,航班号,飞机号,星期几,容量,余票数
        Flight flight;
        size_t pos = line.find(',');
        flight.destination = line.substr(0, pos);
        line.erase(0, pos + 1);

        pos = line.find(',');
        flight.flightNumber = line.substr(0, pos);
        line.erase(0, pos + 1);

        pos = line.find(',');
        flight.airplaneNumber = line.substr(0, pos);
        line.erase(0, pos + 1);

        pos = line.find(',');
        flight.dayOfWeek = stoi(line.substr(0, pos));
        line.erase(0, pos + 1);

        pos = line.find(',');
        flight.capacity = stoi(line.substr(0, pos));
        line.erase(0, pos + 1);

        flight.remainingTickets = stoi(line);

        flights.push_back(flight);
    }
    file.close();
    // 从文件中读取航班信息并存储到 flights 向量中
    // 格式可以是 CSV、JSON 等，这里每行为一个航班信息
}



// 修改文件中的航班信息
void FlightBookingSystem::modifyFlightInfo(const string& flightNumber,const string& airphoneNumber, const Flight& newFlightInfo) {
    for (Flight& flight : flights) {
        if (flight.flightNumber == flightNumber && flight.airplaneNumber == airphoneNumber) {
            // 找到对应航班，修改信息
            flight.destination = newFlightInfo.destination;
            flight.capacity=newFlightInfo.capacity;
            flight.remainingTickets=newFlightInfo.remainingTickets;
            break;
        }
    }

    // 更新航班数据文件
    ofstream outFile(flight_filename);
    if (!outFile.is_open()) {
        cout << "无法打开航班数据文件以写入" << endl;
        return;
    }

    // 将更新后的航班信息写入文件
    for (const Flight& flight : flights) {
        outFile << flight.destination << "," << flight.flightNumber << "," << flight.airplaneNumber << ","
                << flight.dayOfWeek << "," << flight.capacity << "," << flight.remainingTickets << endl;
    }
    outFile.close();

    cout << "航班信息已成功更新并写入文件" << endl;
}




// 从文件加载航班乘客信息
void FlightBookingSystem::loadPassengersFromFile(const string& filename) {
    ifstream file(filename);
    if (!file.is_open()) {
        cout << "无法打开乘客数据文件以加载" << endl;
        return;
    }

    string line;
    while (getline(file, line)) {
        // 解析文件中的乘客信息
        stringstream ss(line);
        string flightNumber, passengerName;
        int cabinClass;
        ss >> flightNumber >> passengerName >> cabinClass;
        // 根据航班号查找对应的航班
        Flight* flight = findFlightByNumber(flightNumber);
        if (flight) {
            // 创建乘客对象
            Passenger passenger;
            passenger.name = passengerName;
            passenger.cabinClass = cabinClass;

            // 将乘客添加到航班的已订票乘客列表中
            flight->bookedPassengers.push_back(passenger);
        } else {
            cout << "错误：没有找到对应的航班！" << flightNumber << endl;
        }
    }
    file.close();

}




// 更新航班乘客信息到文件
void FlightBookingSystem::updatePassengersToFile(const string& filename) {
    ofstream file(filename);
    if (!file.is_open()) {
        cout << "无法打开乘客数据文件以更新" << endl;
        return;
    }

    // 遍历所有航班
    for (const Flight& flight : flights) {
        // 将航班的已订票乘客信息写入文件
        for (const Passenger& passenger : flight.bookedPassengers) {
            file << flight.flightNumber << " " << passenger.name << " " << passenger.cabinClass << endl;
        }
    }

    file.close();
    cout << "乘客信息已成功更新并写入文件" << endl;
}




// 从文件加载候补乘客信息
void FlightBookingSystem::loadCandidatePassengersFromFile(const string& filename) {
    ifstream file(filename);
    if (!file.is_open()) {
        cout << "无法打开候补乘客数据文件以加载" << endl;
        return;
    }

    string line;
    while (getline(file, line)) {
        // 解析文件中的候补乘客信息
        stringstream ss(line);
        string flightNumber, passengerName;
        int cabinClass;
        ss >> flightNumber >> passengerName >> cabinClass;
        // 根据航班号查找对应的航班
        Flight* flight = findFlightByNumber(flightNumber);
        if (flight) {
            // 创建乘客对象
            Passenger passenger;
            passenger.name = passengerName;
            passenger.cabinClass = cabinClass;

            // 将乘客添加到航班的候补乘客队列中
            flight->waitingList.push(passenger);
        } else {
            cout << "错误：没有找到对应的航班！" << flightNumber << endl;
        }
    }
    file.close();

}




// 更新航班候补乘客信息到文件
void FlightBookingSystem::updateCandidatePassengersToFile(const string& filename) {
    ofstream file(filename);
    if (!file.is_open()) {
        cout << "无法打开候补乘客数据文件以更新" << endl;
        return;
    }

    // 遍历所有航班
    for (Flight& flight : flights) {
        //创建一个辅助队列
        queue<Passenger> temp;
        // 将航班的候补乘客信息写入文件
        while(!flight.waitingList.empty()){
            file << flight.flightNumber << " " << flight.waitingList.front().name << " " << flight.waitingList.front().cabinClass << endl;
            temp.push(flight.waitingList.front());
            flight.waitingList.pop();
        }
        while(!temp.empty()){
            flight.waitingList.push(temp.front());
            temp.pop();
        }
    }

    file.close();
    cout << "乘客信息已成功更新并写入文件" << endl;
}





// 构造函数
FlightBookingSystem::FlightBookingSystem(const string& filename1 , const string& filename2 , const string& filename3) {
    loadFlightsFromFile(filename1);
    flight_filename = filename1;
    loadPassengersFromFile(filename2);
    passenger_filename = filename2;
    loadCandidatePassengersFromFile(filename3);
    candidatepassenger_filename = filename3;
}




// 通过目的地查询航班信息
void FlightBookingSystem::queryFlight(const string& destination,QTextBrowser *qtb) {
    int i=0;
    qtb->append("查询航班信息："+QString::fromStdString(destination)+QString('\n'));
    cout << "查询航班信息：" << destination << endl;
    for (const auto& flight : flights) {
        if (flight.destination == destination) {
            qtb->append( "目的地: "+QString::fromStdString(flight.destination)+QString('\n'));
            cout << "目的地: " << flight.destination << endl;
            qtb->append("航班号: "+QString::fromStdString(flight.flightNumber)+QString('\n'));
            cout << "航班号: " << flight.flightNumber << endl;
            qtb->append("飞机号: "+ QString::fromStdString(flight.airplaneNumber)+QString('\n'));
            cout << "飞机号: " << flight.airplaneNumber << endl;
            qtb->append("星期几: " + QString::number(flight.dayOfWeek)+QString('\n'));
            cout << "星期几: " << flight.dayOfWeek << endl;
            qtb->append("剩余票数: " + QString::number(flight.remainingTickets)+QString('\n'));
            cout << "剩余票数: " << flight.remainingTickets << endl;
            qtb->append(QString('\n'));
            cout << endl;
            i++;
        }
    }
    if(i>0){
        return;
    }
    else{
    qtb->append("未找到目的地为 " + QString::fromStdString(destination) + " 的航班信息"+QString('\n'));
    cout << "未找到目的地为 " << destination << " 的航班信息" << endl;
    }
}





// 订票
void FlightBookingSystem::bookTicket(const string& flightNumber , int quantity) {
    // 遍历航班列表，查找匹配航班号的航班
    for (Flight& flight : flights) {
        if (flight.flightNumber == flightNumber) {

            // 检查航班是否还有余票
            if (flight.remainingTickets >= quantity) {
                // 若余票足够，直接订票
                for (int i = 0; i < quantity; ++i) {
                    // 模拟一个新乘客
                    Passenger passenger;
                    QEventLoop eventLoop;
                    this->page2_1=new Form2_1(passenger,i,quantity,flight,eventLoop,1,last);
                    this->page2_1->show();

                    //创建一个事件循环
                    eventLoop.exec();
                    }
                // 更新剩余票额
                flight.remainingTickets -= quantity;
                updatePassengersToFile(passenger_filename);
                modifyFlight(flight.flightNumber,flight.airplaneNumber,flight);
                return; // 订票成功，退出函数

            } else {
            QEventLoop eventLoop1;
                this->page2_2_1=new Form2_2_1(eventLoop1);
            this->page2_2_1->show();
                //创建一个事件循环
                eventLoop1.exec();

                if(flight.remainingTickets > 0){
                    QEventLoop eventLoop2;
                    int a_choice;
                    this->page2_2=new Form2_2(eventLoop2,a_choice);
                    this->page2_2->show();

                    //创建一个事件循环
                    eventLoop2.exec();

                    if(a_choice){
                        for (int i = flight.remainingTickets; i > 0 ; --i) {
                            // 模拟一个新乘客
                            Passenger passenger;
                            QEventLoop eventLoop3;
                            this->page2_1=new Form2_1(passenger,i,2,flight,eventLoop3,2,last);
                            this->page2_1->show();

                            eventLoop3.exec();
                        }
                        //票数变更
                        quantity -= flight.remainingTickets;
                        flight.remainingTickets = 0;
                        updatePassengersToFile(passenger_filename);
                        modifyFlight(flight.flightNumber,flight.airplaneNumber,flight);
                    }
                }

                // 若余票不足，提示用户并提供其他选择
                int select;
                QEventLoop eventLoop4;
                this->page2_4=new Form2_4(eventLoop4,select);
                Widget::connect(this->page2_4,SIGNAL(back()),this->last,SLOT(comeBackToPrev2_4()));
                this->page2_4->show();

                eventLoop4.exec();

                switch (select) {
                case 1:{
                    for (int i = 0; i < quantity; ++i) {
                        // 模拟一个新乘客
                        Passenger passenger;
                        QEventLoop eventLoop5;
                        this->page2_1=new Form2_1(passenger,i,quantity,flight,eventLoop5,3,last);
                        this->page2_1->show();

                        eventLoop5.exec();
                    }
                    updateCandidatePassengersToFile(candidatepassenger_filename);
                    break;
                }
                case 2:{
                    string destination = flight.destination;
                    this->page1_1=new Form1_1(*this,destination);
                    Widget::connect(this->page1_1,SIGNAL(back()),this->last,SLOT(comeBackToPrev1_1()));
                    this->page1_1->show();
                    break;
                }
                case 3:{
                    break;
                }
                default:{
                    break;
                }
                }
                // 这里可以提供排队候补或其他可选择航班的功能
                return; // 退出函数
            }
        }
    }
    // 若未找到匹配航班号的航班，提示用户重新输入
    this->page2_5=new Form2_5;
    Widget::connect(this->page2_5,SIGNAL(back()),this->last,SLOT(comeBackToPrev2_5()));
    this->page2_5->show();
}






// 退票
void FlightBookingSystem::cancelTicket(const string& flightNumber, const string& passengerName) {
    // 遍历航班列表，查找匹配航班号的航班
    for (Flight& flight : flights) {
        if (flight.flightNumber == flightNumber) {

            // 在已订票乘客列表中查找匹配乘客姓名的乘客
            for (Passenger& passenger : flight.bookedPassengers) {
                if (passenger.name == passengerName) {
                    // 找到匹配的乘客，执行退票操作
                    // 从已订票乘客列表中移除乘客
                    flight.bookedPassengers.erase(
                        remove_if(flight.bookedPassengers.begin(), flight.bookedPassengers.end(),[&](const Passenger& p) { return p.name == passengerName; }),flight.bookedPassengers.end());

                    this->page3_1=new Form3_1;
                    Widget::connect(this->page3_1,SIGNAL(back()),this->last,SLOT(comeBackToPrev3_1()));
                    this->page3_1->show();

                    //判断是否执行候补功能
                    if(flight.remainingTickets==0){
                        //实行候补
                        flight.bookedPassengers.push_back(flight.waitingList.front());
                        flight.waitingList.pop();
                        updateCandidatePassengersToFile(candidatepassenger_filename);
                    }
                    //不实行候补
                    else{
                        flight.remainingTickets++;//增加剩余票额
                    }
                    updatePassengersToFile(passenger_filename);
                    modifyFlight(flight.flightNumber,flight.airplaneNumber,flight);
                    return; // 退票成功，退出函数
                }
            }
            // 若未找到匹配的乘客，提示用户重新输入
            this->page2_4_2=new Form2_4_2;
            Widget::connect(this->page2_4_2,SIGNAL(back()),this->last,SLOT(comeBackToPrev2_4_2()));
            this->page2_4_2->show();
            return; // 退出函数
        }
    }
    // 若未找到匹配航班号的航班，提示用户重新输入
    this->page2_5=new Form2_5;
    Widget::connect(this->page2_5,SIGNAL(back()),this->last,SLOT(comeBackToPrev2_5()));
    this->page2_5->show();
}





// 修改航班信息的公共接口
void FlightBookingSystem::modifyFlight(const string& flightNumber, const string& airphoneNumber, Flight& newFlightInfo) {
    modifyFlightInfo(flightNumber,airphoneNumber,newFlightInfo);
}




// 显示航班信息
void FlightBookingSystem::displayFlights(QTextBrowser *qtb) {
    qtb->append( "所有航班信息：" +QString('\n'));
    for (const auto& flight : flights) {
        qtb->append( "目的地: " +QString::fromStdString(flight.destination)+QString('\n'));
        qtb->append( "航班号: " +QString::fromStdString(flight.flightNumber)+QString('\n'));
        qtb->append( "飞机号: " +QString::fromStdString(flight.airplaneNumber)+QString('\n'));
        qtb->append( "星期几: " +QString::number(flight.dayOfWeek)+QString('\n'));
        qtb->append( "容量: " + QString::number(flight.capacity)+QString('\n'));
        qtb->append( "剩余票数: " +QString::number(flight.remainingTickets)+QString('\n'));
        qtb->append(QString('\n'));
    }
}





//判断能否修改航线数据
bool FlightBookingSystem::ismodifyFlights(const string& flightNumber,const string& airphoneNumber){
    for (const auto& flight : flights) {
        if (flight.flightNumber == flightNumber && flight.airplaneNumber==airphoneNumber) {
            //当航班已经有乘客时，不能修改航班数据
            if(flight.remainingTickets<flight.capacity){
                this->page3_2=new Form3_2;
                Widget::connect(this->page3_2,SIGNAL(back()),this->last,SLOT(comeBackToPrev3_2()));
                this->page3_2->show();
                return 0;
            }
            return 1;
        }
    }
    this->page2_5=new Form2_5;
    Widget::connect(this->page2_5,SIGNAL(back()),this->last,SLOT(comeBackToPrev2_5()));
    this->page2_5->show();
    return 0;
}





//通过航班号找到对应航班的指针
Flight* FlightBookingSystem::findFlightByNumber(const string& flightNumber) {
    for (Flight& flight : flights) {
        if (flight.flightNumber == flightNumber) {
            return &flight;
        }
    }
    return nullptr;
}
